#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import getpass
import pexpect


REMOTE_PATH = "/home/docker/npm/letsencrypt/live/npm-1"
NC_PATH = "/mnt/disk2/docker_data/nc/proxy/ssl_certs/"
OFFICE_PATH = "/home/bongem/docker_data/onlyoffice/data/certs"
TEMP_DIR = "./.tmp_cert"

username = input("请输入用户名:")
host = input("请输入服务器:")
pwd = getpass.getpass("请输入密码:")
password_key = '.*assword.*'

# 创建临时目录
os.system(f"mkdir {TEMP_DIR}")
# "resut = os.popen(cmd).read().strip()"
command = f'scp {username}@{host}:{REMOTE_PATH}/*.pem {TEMP_DIR}'
print("从远程路径下载证书...")
try:
    execute = pexpect.spawn(command)
    execute.expect(password_key)
    execute.sendline(pwd)
    execute.expect(pexpect.EOF)
    print("下载证书成功")

    print("应用证书到nc")
    # os.system(f"more {TEMP_DIR}/fullchain.pem > {NC_PATH}/fullchain.pem")
    # os.system(f"more {TEMP_DIR}/privkey.pem > {NC_PATH}/privkey.pem")

    print("应用证书到office")
    os.system(f"more {TEMP_DIR}/privkey.pem > {OFFICE_PATH}/onlyoffice.key")
    os.system(f"more {TEMP_DIR}/cert.pem > {OFFICE_PATH}/onlyoffice.crt")

    print("重启nc和office服务...")
    os.system("docker restart onf-7.3 nc-app-1 nc-proxy-1")
except Exception as e:
    print("下载证书失败.", e)
finally:
    os.system(f"rm -rf {TEMP_DIR}")
